package StudyCode.summary.myfile;

import java.util.StringTokenizer;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReturnSourceTargetRelativePath {
	public static void main(String[] args) {
		System.out.println("E:/Copy/1/2 与 E:/Copy 的相对路径是: " + makeRelative("E:/Copy/1/2", "E:/Copy"));
	}

	public static String makeRelative(String origin, String path) {
		boolean trailingSlash = path.endsWith("/");
		StringBuffer sb = new StringBuffer(40);
		StringTokenizer originTokenizer = new StringTokenizer(origin, "/",
				false);
		StringTokenizer pathTokenizer = new StringTokenizer(path, "/",
				false);

		String firstTokenNotInCommon = null;
		while (originTokenizer.hasMoreTokens()
				&& pathTokenizer.hasMoreTokens()
				&& firstTokenNotInCommon == null) {
			firstTokenNotInCommon = pathTokenizer.nextToken();
			if (originTokenizer.nextToken().equals(firstTokenNotInCommon))
				firstTokenNotInCommon = null;
		}

		int stepsBack = originTokenizer.countTokens();
		if (firstTokenNotInCommon != null)
			stepsBack++;
		for (int i = 0; i < stepsBack; i++) {
			sb.append("..");
			if (trailingSlash || pathTokenizer.hasMoreTokens()
					|| firstTokenNotInCommon != null || i < stepsBack - 1)
				sb.append('/');
		}

		if (firstTokenNotInCommon != null) {
			sb.append(firstTokenNotInCommon);
			if (trailingSlash || pathTokenizer.hasMoreTokens())
				sb.append('/');
		}
		while (pathTokenizer.hasMoreTokens()) {
			String part = pathTokenizer.nextToken();
			sb.append(part);
			if (trailingSlash || pathTokenizer.hasMoreTokens())
				sb.append('/');
		}
		if (sb.length() == 0)
			return "";
		else
			return sb.toString();
	}
}
